import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElSpace,
  ElLink,
  ElMessage,
  ElMessageBox,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElIcon
} from 'element-plus'
import { Operation } from '@element-plus/icons-vue'

import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { fnStateEnum, lampModel } from '~/store/monitor/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import ColorfulBadge from '~/components/ColorfulBadge'
import ParamsSet from './paramsSet'
import AddSingleLamp from './addSingleLamp'
import styles from '../../index.module.scss'
import DetailPage from './detailPage'
import DimModel from '../../components/dimModel'
import useWebsocket from '~/hooks/useWebsocket'
import NoticeMes from '../../components/noticeMes'
import RoadManageImportModal from './importModal' // 导入

// 单灯设备管理
export default defineComponent(function SingleLampManagement() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const deviceViewRef = ref()
  const paramsSetRef = ref()
  const addLampRef = ref()
  const dimModelRef = ref()
  const webSocketRef = useWebsocket('/websocket/protocol/lampctrl', {
    // 接收数据回调
    onmessage: () => {}
  })
  const noticeRef = ref()
  const singleLampState = useVuexGetters('singleLamp', [
    'communicationStateOpt',
    'communicationStateEnum',
    'devBrand',
    'devModel',
    'runStatusOpt',
    'runStatusNum'
  ])
  const userState = useVuexGetters('user', ['permission'])
  const userStateToken = useVuexGetters('user', ['token'])
  const state = reactive({
    exportVisible: false,
    operations: [
      {
        label: '关灯',
        value: 0
      },
      {
        label: '开灯',
        value: 1
      },
      {
        label: '调光',
        value: 2
      }
    ],
    dimVisible: false,
    importVisible: false
  })

  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '设备名称',
      prop: 'name',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '设备编号',
      prop: 'code',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '设备品牌',
      prop: 'brandName',
      minWidth: 160,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备型号',
      prop: 'modelName',
      minWidth: 160,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '所属灯杆',
      prop: 'lampPostName',
      minWidth: 160,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '故障状态',
      prop: 'runStatus',
      minWidth: 160,
      align: 'center',
      enumValues: singleLampState.runStatusNum,
      showOverflowTooltip: true,
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.runStatus as unknown as number}
          options={{ success: 1, info: 0, warning: 2 }}
        />
      )
    },
    {
      label: '在线状态',
      prop: 'onlineState',
      minWidth: 160,
      align: 'center',
      enumValues: singleLampState.communicationStateEnum,
      showOverflowTooltip: true,
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.onlineState as unknown as number}
          options={{ success: 1, info: 0, warning: 2 }}
        />
      )
    },
    {
      label: '更新人',
      prop: 'updateUser',
      minWidth: 160,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 160,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 400,
      align: 'center',
      fixed: 'right',
      // unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => infoOpen(row.id)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 详情
          </ElLink>
          {userState.permission.value.has('lamp_node_setting') && (
            <ElLink type="primary" onClick={() => handleChangeParamsSetModal(row)}>
              <AliIcon type="icon-shezhi" />
              &nbsp; 参数设置
            </ElLink>
          )}
          {userState.permission.value.has('lamp_node_update') && (
            <ElLink type="primary" onClick={() => handleChangeAddsingleLampModal(row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('lamp_node_remove') && (
            <ElLink type="primary" onClick={() => handleDeleteSingleLamp(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
          {userState.permission.value.has('lamp_node_remove') && (
            <ElLink type="primary" onClick={() => synchronousAsset(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 同步资产
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  //  跳转到详情
  const infoOpen = (id?: string) => {
    deviceViewRef.value.open(id)
  }
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  // 参数设置
  const handleChangeParamsSetModal = (record?: FormValuesType) => {
    paramsSetRef.value.openParams('one', record)
  }
  // 批量参数设置
  const handleChangeMulParamsSetModal = () => {
    if (!proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要下发的设备' })
      return
    }

    const params = proSaasTableRef.value!.selecteds
    paramsSetRef.value.openParams('more', params)
  }
  // 打开新增/编辑单灯弹窗
  const handleChangeAddsingleLampModal = (record?: FormValuesType) => {
    addLampRef.value.openAdd(record)
  }
  const handleChangeValueActionSearchList = () => {
    nextTick(proSaasTableRef.value!?.toSearch)
  }
  // 删除单灯
  const handleDeleteSingleLamp = (record: FormValuesType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {<p class="delete-title">确认删除数据？</p>}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('singleLamp/DeviceRemove', { ids: params }).then(async (result) => {
          if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          proSaasTableRef.value!?.toSearch()
        })
      })
      .catch(() => {})
  }
  // 同步资产
  const synchronousAsset = (record: any) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {<p class="delete-title">确认同步资产？</p>}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('singleLamp/SyncLamppost', { ids: record.id }).then(async (result) => {
          if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          proSaasTableRef.value!?.toSearch()
        })
      })
      .catch(() => {})
  }
  // 操作指令
  const handleOrder = (type: any) => {
    if (!proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要操作的设备' })
      return
    }
    let text = ''
    let title = ''
    if (type.value === 1) {
      text = '确认对选中的设备下发开灯命令？'
      title = '开灯'
    } else if (type.value === 0) {
      text = '确认对选中的设备下发关灯命令？'
      title = '关灯'
    } else if (type.value === 2) {
      text = '确认对选中的设备下发调光命令？'
    }

    const params = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    const tokenValue = userStateToken.token.value

    ElMessageBox({
      title: '确认提示',
      message: <section class={styles['delete-confirm-box']}>{<p>{text}</p>}</section>,
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        if (type.value === 1 || type.value === 0) {
          await store
            .dispatch('singleLamp/SinglelampSwitch', { lampNodeId: params, opr: type.value })
            .then(async (result) => {
              if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
            })
          const arr = proSaasTableRef.value!.selecteds?.map((item: any) => item.id)
          const codes = proSaasTableRef.value!.selecteds?.map((item: any) => item.code)
          arr?.forEach((item) => {
            const websockParams = {
              deviceId: item,
              commandCode: '004',
              token: tokenValue
            }
            webSocketRef.value!.send(JSON.stringify(websockParams))
          })
          noticeRef.value.initMes({
            deviceId: params,
            commandCode: '004',
            token: userState.token.value,
            title,
            key: '004',
            arrStr: codes.join(','),
            callBack: () => {}
          })
        } else {
          dimChange()
        }
      })
      .catch(() => {})
  }
  // 调光
  const dimLight = async () => {
    const arr = proSaasTableRef.value!.selecteds?.map?.((item: any) => item.id)
    const ids = arr.join(',')
    const codes = proSaasTableRef.value!.selecteds?.map?.((item: any) => item.code)
    const dimNum = dimModelRef.value.ruleForm.dimNum
    const res = await store.dispatch('singleLamp/SinglelampDim', {
      lampNodeId: ids,
      dim: dimNum
    })
    arr.forEach((element: any) => {
      const websockParams = {
        deviceId: element.id,
        commandCode: '005',
        token: userState.token.value
      }
      webSocketRef.value!.send(JSON.stringify(websockParams))
    })
    noticeRef.value.initMes({
      deviceId: ids,
      commandCode: '005',
      token: userState.token.value,
      title: '调光',
      key: '005',
      arrStr: codes.join(','),
      callBack: () => {}
    })
    if (res.code === 200) {
      ElMessage({
        message: '操作成功',
        type: 'success',
        duration: 2000
      })
      dimChange()
    }
  }
  const swInitFun = (data?: any) => {
    if (data.result === '2') {
      noticeRef.value.stateFun({
        key: data.commandCode,
        state: 'error',
        errText: data.data.message || '命令下发失败！'
      })
      return false
    }
    // 单个回路
    if (data.data.status === 1)
      noticeRef.value.stateFun({
        key: data.commandCode,
        id: ''
      })
  }
  const dimChange = () => {
    state.dimVisible = !state.dimVisible
  }
  // 切换导入弹框
  const handleChangeImprotModal = () => {
    state.importVisible = !state.importVisible
    if (!state.importVisible) proSaasTableRef.value!?.toSearch()
  }

  onMounted(() => {
    //  在线状态
    store.dispatch('singleLamp/CommunicationStateGet', { code: 'onlineStatus' })
    //  单灯设备型号
    store.dispatch('singleLamp/GetModelList')
    //  故障状态
    store.dispatch('singleLamp/RunstatusStateGet', { code: 'runStatus' })
    window.swInitFun = swInitFun
  })
  return () => (
    <ElCard>
      <ProSaasTable<FormValuesType>
        tableId="monitor_singleLamp_index"
        ref={proSaasTableRef}
        columns={columns}
        searchParams={formValues}
        hasSelection
        dispatchType="singleLamp/DeviceListGet"
        searchFormProps={{
          model: formValues
        }}
        headerTitle={
          <>
            {userState.permission.value.has('lamp_node_option') && (
              <ElDropdown
                trigger="click"
                onCommand={handleOrder}
                style="margin-right:10px"
                v-slots={{
                  dropdown: () => (
                    <ElDropdownMenu>
                      {state.operations.map((item) => (
                        <ElDropdownItem command={item}>{item.label}</ElDropdownItem>
                      ))}
                    </ElDropdownMenu>
                  )
                }}
              >
                <ElButton type="primary">
                  <ElIcon>
                    <Operation />
                  </ElIcon>
                  &nbsp; 操作指令
                </ElButton>
              </ElDropdown>
            )}
            {userState.permission.value.has('lamp_node_setting') && (
              <ElButton type="primary" onClick={handleChangeMulParamsSetModal}>
                <AliIcon type="icon-shezhi" />
                &nbsp; 参数设置
              </ElButton>
            )}
            {userState.permission.value.has('lamp_node_add') && (
              <ElButton type="primary" onClick={() => handleChangeAddsingleLampModal()}>
                <AliIcon type="icon-xinzeng" />
                &nbsp; 新增
              </ElButton>
            )}
            <ElButton type="primary" onClick={() => handleChangeImprotModal()}>
              <AliIcon type="icon-daoru" />
              &nbsp; 导入
            </ElButton>
          </>
        }
        searchformResponsiveCol={[
          <ElFormItem key="name" prop="name" label="">
            <ElInput
              v-model={formValues.name}
              placeholder="设备名称"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="onlineState" prop="onlineState">
            <ElSelect
              v-model={formValues.onlineState}
              clearable
              placeholder="在线状态"
              onChange={clearSearchTable}
            >
              {singleLampState.communicationStateOpt?.value?.map((item: fnStateEnum) => (
                <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
              ))}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="runStatus" prop="runStatus">
            <ElSelect
              v-model={formValues.runStatus}
              clearable
              placeholder="故障状态"
              onChange={clearSearchTable}
            >
              {singleLampState.runStatusOpt?.value?.map(
                (item: fnStateEnum) =>
                  item?.dictValue !== '未激活' && (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                  )
              )}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="modelId" prop="modelId">
            <ElSelect
              v-model={formValues.modelId}
              clearable
              placeholder="设备型号"
              onChange={clearSearchTable}
            >
              {singleLampState.devModel?.value?.map((item: lampModel) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id} />
              ))}
            </ElSelect>
          </ElFormItem>
        ]}
      />

      <AddSingleLamp onSubmitForm={handleChangeValueActionSearchList} ref={addLampRef} />

      <DetailPage ref={deviceViewRef} />
      <ParamsSet ref={paramsSetRef} />
      {state.dimVisible && (
        <DimModel ref={dimModelRef} onSubmitForm={dimLight} cancel={dimChange} />
      )}
      <NoticeMes ref={noticeRef} />
      {state.importVisible && <RoadManageImportModal doCancel={handleChangeImprotModal} />}
    </ElCard>
  )
})
